import axios from 'axios';
import { Message } from 'element-ui'
import { getCookie } from '@/utils/util.js';
import router from '@/router'
import { serverUrl } from '@/utils/server.js'
/**
 * axios实例
 */
const request = axios.create({
  baseURL: '/adminApi/',//serverUrl.baseURL
  timeout: 10000,
  headers: {
    
  }
});

/**
 * 请求前添加token
 */
request.interceptors.request.use(function(config) {
  config.headers['token'] = getCookie('token') !== '' ? getCookie('token') : ''; // 获取token 也就是说在设置的时候也要设置成token
  return config;
});
export default request;
/**
 * 请求回来处理数据
 */
request.interceptors.response.use(function(res) {
  if (res.config.url.indexOf('getQrCode') !== -1) {
    return res.request.response
  }
  var result = JSON.parse(res.request.response);
  if ((result.code === 200 || result.code === 201) || result.errcode === 0) {
    return result;
  } else {
    Message({
      message: result.message ? result.message : result.errmsg,
      type: 'error'
    });
    if (result.code === 401) {
      router.push({path: '/login'})
    }
    return Promise.reject(result);
  }
});
